package com.productAndConsume;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 *  Condition 实现精准通知唤醒
 *  要求A执行完了执行B，B执行完了执行C，C执行完了执行D. condition根据条件进入 逻辑不对的话会死锁
 *
 *  加多个监视器，通过监视器来判断唤醒的是哪一个人
 *  设置多个同步监视器，每个监视器监视一个线程
 * */
public class TestLockPC2 {
    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(()->{
            for (int i = 0; i < 11; i++) {
                data3.A();
            }
        }).start();
        new Thread(()->{
            for (int i = 0; i < 11; i++) {
                data3.B();
            }
        }).start();
        new Thread(()->{
            for (int i = 0; i < 11; i++) {
                data3.C();
            }
        }).start();
    }
}
//资源类
class Data3{

    private Lock lock = new ReentrantLock();
    //设置多个监视器
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    // 1A 2B 3C
    private int num = 1;
    public void A(){
        lock.lock();
        try{
            //等于1的话 跳过while    为1时的condition
            while (num!=1){
                condition1.await();// 进入此方法的线程挂起 进入condition queue-队列
            }
            System.out.println(Thread.currentThread().getName()+"=>AAA");
            //精准唤醒
            num=2;
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void B(){
        lock.lock();
        try{
            // 不等于2就进去等到 等于2就不用等 直接同步
            while (num!=2){
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>BBB");
            //精准唤醒
            num=3;
            condition3.signal(); //bug测试 改为condition1的话
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void C(){
        lock.lock();
        try{
            //等于 2 1的话当前线程就进去等到
            while (num!=3){
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>CCC");
            //精准唤醒
            num=1;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


}
